package v1

import (
	"fmt"
	"gin-luban-server/global"
	"gin-luban-server/model/request"
	"gin-luban-server/model/response"
	"gin-luban-server/service"
	"gin-luban-server/utils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"strconv"
	"strings"
	"time"
)

// @Tags DeployAppJenkins
// @msp 创建项目应用jenkinsJOb
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.DeployAppJenkins true "body"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /deploy/jenkins/createDeployAppJenkins [post]

func CreateDeployAppJenkins(c *gin.Context) {
	var R request.GetById
	_ = c.ShouldBindJSON(&R)
	if code,msg := utils.Validate(&R);code != response.SUCCESS_VALIDATE {
		response.FailValidateMessage(msg,c)
		return
	}
	if err := service.CreateJenkinsJobFile(R.Id); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
		response.FailWithMessage("创建失败" + err.Error(), c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}




// @Tags DeployAppJenkins
// @msp 更新项目应用jenkinsJob
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.DeployAppJenkins true "body"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /deploy/jenkins/updateDeployAppJenkins [put]

func UpdateDeployAppJenkins(c *gin.Context) {
	var R request.GetById
	_ = c.ShouldBindJSON(&R)
	if code,msg := utils.Validate(&R);code != response.SUCCESS_VALIDATE {
		response.FailValidateMessage(msg,c)
		return
	}
	if err := service.UpdateJenkinsJobFile(R.Id); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
		response.FailWithMessage("更新失败" + err.Error(), c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// @Tags GetJenkinsBuildJob
// @msp 构建job
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.DeployBuildHistory true "body"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /deploy/jenkins/getJenkinsBuildJob [post]

func StartJenkinsJobBuild(c *gin.Context) {
	// 需要获取用户信息 部署用户
	claims, _ := c.Get("claims")
	waitUse := claims.(*request.CustomClaims)

	var R request.JenkinsJobBuildParams
	_ = c.ShouldBindJSON(&R)
	if code,msg := utils.Validate(&R);code != response.SUCCESS_VALIDATE {
		response.FailValidateMessage(msg,c)
		return
	}
	if buildNumber, err := service.StartJenkinsJobBuild(R, waitUse.Username, waitUse.NickName); err != nil {
		global.GVA_LOG.Error("触发构建失败!", zap.Any("err", err))
		response.FailWithMessage("触发构建失败" + err.Error(), c)
	} else {
		response.OkWithDetailed(gin.H{"build_number": buildNumber},"触发构建成功", c)
	}
}

// @Tags GetJenkinsBuildJob
// @msp 构建job
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.DeployBuildHistory true "body"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /deploy/jenkins/getJenkinsBuildJobLogs [post]
func GetJenkinsBuildJobLogs(c *gin.Context) {
	var R request.JenkinsBuildJobLogsParams
	_ = c.ShouldBindJSON(&R)
	if code,msg := utils.Validate(&R);code != response.SUCCESS_VALIDATE {
		response.FailValidateMessage(msg,c)
		return
	}
	if logContent, err := service.GetJenkinsBuildJobLogs(R); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Any("err", err))
		response.FailWithMessage("查询失败" + err.Error(), c)
	} else {
		response.OkWithDetailed(gin.H{"log": logContent}, "成功", c)
	}
}

// web socket 获取构建日志
func GetJenkinsBuildJobLogsWS(c *gin.Context) {

	jobName := c.Query("apps_job_name")
	buildNumber,_ := strconv.ParseInt(c.Query("build_number"),10, 64)
	deployType := c.Query("deploy_type")
	var R request.JenkinsBuildJobLogsParams
	R.BuildNumber = buildNumber
	R.AppsJobName = jobName
	R.DeployType = deployType

	fmt.Println(R)
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		global.GVA_LOG.Error("upgrade:", zap.Any("err", err))
		return
	}
	defer ws.Close()
	// 这个地方用ws实现
	tick := time.Tick(time.Duration(2) * time.Second)
	for i := range tick {
		fmt.Println("websocket:", i)
		//time.Sleep(2 * time.Second)
		logContent, err := service.GetJenkinsBuildJobLogs(R)
		if err != nil {
			global.GVA_LOG.Error("获取build日志失败:", zap.Any("err", err))
			break
		}
		//println(conS.Content)   // string类型
		// 2. 发送信息
		err = ws.WriteMessage(websocket.TextMessage, []byte(logContent))
		if strings.Contains(logContent, "Finished:") {
			break
		}
	}

}

// 创建回滚的-jenkins job
func CreateRollbackJenkinsJob(c *gin.Context) {
	if err := service.CreateRollbackJenkinsJob(); err != nil {
		response.FailWithMessage("JOB创建成功" + err.Error(), c)
	} else {
		response.OkWithData("JOB创建成功",c)

	}

}
// 回滚触发job
func RollbackJenkinsJobBuild(c *gin.Context) {
	// 需要获取用户信息 部署用户
	claims, _ := c.Get("claims")
	waitUse := claims.(*request.CustomClaims)

	var R request.JenkinsJobRollbackParams
	_ = c.ShouldBindJSON(&R)

	if code,msg := utils.Validate(&R);code != response.SUCCESS_VALIDATE {
		response.FailValidateMessage(msg,c)
		return
	}
	if buildNumber, err := service.RollbackJenkinsJobBuild(R, waitUse.Username, waitUse.NickName); err != nil {
		global.GVA_LOG.Error("触发构建失败!", zap.Any("err", err))
		response.FailWithMessage("触发构建失败" + err.Error(), c)
	} else {
		response.OkWithDetailed(gin.H{"build_number": buildNumber},"触发构建成功", c)
	}
}